import time
import board
import digitalio
import analogio

work_led = digitalio.DigitalInOut(board.GP3)
work_led.switch_to_output(value=False, drive_mode=digitalio.DriveMode.PUSH_PULL)

ADC = analogio.AnalogIn(board.GP47)

all_fall = 3.028
sw4_value = 2.94021
sw3_value = 2.98684
sw2_value = 3.01074
sw1_value = 3.02388

def choose_sw(ADC_value):
    middle_01 = 3.032
    middle_12 = (sw1_value + sw2_value)/2
    middle_23 = (sw2_value + sw3_value)/2
    middle_34 = (sw3_value + sw4_value)/2
    button_middle = 2
    if (ADC_value > middle_01):
        return 0
    elif (ADC_value > middle_12):
        return 1
    elif (ADC_value > middle_23):
        return 2
    elif (ADC_value > middle_34):
        return 3
    elif (ADC_value > 2.86):
        return 4
    elif (ADC_value >button_middle):
        # 最左边按键
        return 5
    else:
        # 最右边按键
        return 6

if __name__ == "__main__":
    
    while True:
        ADC_result = []
        epochs = 10
        for i in range(epochs):
            ADC_result.append(ADC.value)
        
        ADC_value = sum(ADC_result)/len(ADC_result)
        
        ADC_value = ADC_value * 3.3 / 65535
        
        print("电压值为:",ADC_value)
        
        sw = choose_sw(ADC_value)
        
        print("按键为:%d"%sw)
        
        time.sleep(1)
    

'''
# 估计电压值
result = []
time.sleep(2)
for i in range(100):
    result.append(ADC.value*3.3/65535)
print(sum(result)/len(result))
'''

